<template>
  <div class="model-form">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑模型' : '创建模型' }}</h2>
      <el-button @click="$router.push('/models')">返回列表</el-button>
    </div>
    
    <el-card>
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
        v-loading="loading"
      >
        <el-form-item label="模型名称" prop="name">
          <el-input v-model="form.name" :disabled="isEdit" placeholder="英文名称，用于API和数据库表名" />
          <div class="form-help">英文字母、数字和下划线，不能包含空格，例如: user_profile</div>
        </el-form-item>
        
        <el-form-item label="显示名称" prop="displayName">
          <el-input v-model="form.displayName" placeholder="用于界面显示的名称" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="3" 
            placeholder="模型的详细描述"
          />
        </el-form-item>
        
        <el-divider>字段定义</el-divider>
        
        <div class="fields-container">
          <div v-for="(field, index) in form.fields" :key="index" class="field-item">
            <el-card>
              <template #header>
                <div class="field-header">
                  <span>字段 #{{ index + 1 }}</span>
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="removeField(index)"
                    :disabled="form.fields.length <= 1"
                  >
                    删除
                  </el-button>
                </div>
              </template>
              
              <el-form-item 
                :prop="`fields.${index}.name`" 
                :rules="fieldRules.name"
                label="字段名称"
              >
                <el-input v-model="field.name" placeholder="字段名称，如: username" />
              </el-form-item>
              
              <el-form-item 
                :prop="`fields.${index}.displayName`" 
                :rules="fieldRules.displayName"
                label="显示名称"
              >
                <el-input v-model="field.displayName" placeholder="显示名称，如: 用户名" />
              </el-form-item>
              
              <el-form-item 
                :prop="`fields.${index}.type`" 
                :rules="fieldRules.type"
                label="数据类型"
              >
                <el-select v-model="field.type" placeholder="选择数据类型" style="width: 100%">
                  <el-option label="字符串" value="string" />
                  <el-option label="文本" value="text" />
                  <el-option label="整数" value="integer" />
                  <el-option label="浮点数" value="float" />
                  <el-option label="布尔值" value="boolean" />
                  <el-option label="日期" value="date" />
                  <el-option label="日期时间" value="datetime" />
                  <el-option label="JSON" value="json" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="必填">
                <el-switch v-model="field.required" />
              </el-form-item>
              
              <el-form-item label="描述">
                <el-input 
                  v-model="field.description" 
                  type="textarea" 
                  :rows="2" 
                  placeholder="字段描述"
                />
              </el-form-item>
            </el-card>
          </div>
          
          <div class="add-field">
            <el-button type="primary" @click="addField">
              <el-icon><el-icon-plus /></el-icon>
              添加字段
            </el-button>
          </div>
        </div>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="$router.push('/models')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useModelStore } from '../../stores/model'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const modelStore = useModelStore()

const formRef = ref(null)
const loading = ref(false)

const isEdit = computed(() => route.params.id !== undefined)

// 表单数据
const form = reactive({
  name: '',
  displayName: '',
  description: '',
  fields: [
    {
      name: '',
      displayName: '',
      type: 'string',
      required: false,
      description: ''
    }
  ]
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入模型名称', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  displayName: [
    { required: true, message: '请输入显示名称', trigger: 'blur' }
  ]
}

const fieldRules = {
  name: [
    { required: true, message: '请输入字段名称', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  displayName: [
    { required: true, message: '请输入显示名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择数据类型', trigger: 'change' }
  ]
}

// 添加字段
function addField() {
  form.fields.push({
    name: '',
    displayName: '',
    type: 'string',
    required: false,
    description: ''
  })
}

// 删除字段
function removeField(index) {
  if (form.fields.length > 1) {
    form.fields.splice(index, 1)
  }
}

// 提交表单
async function submitForm() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    loading.value = true
    
    if (isEdit.value) {
      await modelStore.updateModel(route.params.id, form)
      ElMessage.success('模型更新成功')
    } else {
      await modelStore.createModel(form)
      ElMessage.success('模型创建成功')
    }
    
    router.push('/models')
  } catch (err) {
    console.error('表单验证失败:', err)
    if (err.message) {
      ElMessage.error(err.message)
    }
  } finally {
    loading.value = false
  }
}

// 加载模型数据
async function loadModel() {
  if (!isEdit.value) return
  
  try {
    loading.value = true
    const modelData = await modelStore.getModel(route.params.id)
    
    if (!modelData) {
      throw new Error('模型不存在')
    }
    
    // 填充表单数据
    form.name = modelData.name
    form.displayName = modelData.displayName
    form.description = modelData.description
    
    // 确保 fields 是数组
    if (typeof modelData.fields === 'string') {
      try {
        form.fields = JSON.parse(modelData.fields)
      } catch (e) {
        console.error('解析字段失败:', e)
        form.fields = []
      }
    } else {
      form.fields = Array.isArray(modelData.fields) ? modelData.fields : []
    }
    
    // 确保至少有一个字段
    if (!form.fields || form.fields.length === 0) {
      addField()
    }
  } catch (err) {
    ElMessage.error('加载模型失败: ' + err.message)
    router.push('/models')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadModel()
})
</script>

<style scoped>
.model-form {
  padding: 20px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
}

.form-help {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.fields-container {
  margin-bottom: 20px;
}

.field-item {
  margin-bottom: 20px;
}

.field-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.add-field {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 